package com.xoa.service.party;


import com.xoa.dao.party.EnAutoCompanyMapper;
import com.xoa.dao.party.MapOwnerinfoMapper;
import com.xoa.model.party.EnAutoCompany;
import com.xoa.model.users.Users;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 汽修企业
 * Created by gsb on 2018/1/5.
 */
@Service
public class EnAutoCompanyService {

    @Resource
    private EnAutoCompanyMapper enAutoCompanyMapper;
    @Resource
    private MapOwnerinfoMapper mapOwnerinfoMapper;
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-5 下午16:46:51
     * 类介绍  :   新建
     * 构造参数:
     *
     */
    public ToJson<EnAutoCompany> insertSelective(EnAutoCompany enAutoCompany, HttpServletRequest request, String gridLocation){
        ToJson<EnAutoCompany> json = new ToJson<>();
        try {
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            if(gridLocation!=null){
                enAutoCompany.setRemark1(gridLocation);
            }
            enAutoCompany.setCreateUser(user.getUserId());
            enAutoCompany.setCreateTime(DateFormat.getDatestr(new Date()));
            enAutoCompanyMapper.insertSelective(enAutoCompany);
            json.setMsg("成功");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-5 下午16:48:51
     * 类介绍  :   删除
     * 构造参数:
     *
     */
    public ToJson<EnAutoCompany> deleteByPrimaryKey(Integer cid){
        ToJson<EnAutoCompany> json = new ToJson<>();
        try {
            enAutoCompanyMapper.deleteByPrimaryKey(cid);
            json.setMsg("true");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;

    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-5 下午16:48:51
     * 类介绍  :   修改
     * 构造参数:
     *
     */
    public ToJson<EnAutoCompany> updateByPrimaryKeySelective(EnAutoCompany enAutoCompany, HttpServletRequest request, String gridLocation){
        ToJson<EnAutoCompany> json = new ToJson<>();
        try {
            if(gridLocation!=null){
                enAutoCompany.setRemark1(gridLocation);
            }
            enAutoCompanyMapper.updateByPrimaryKeySelective(enAutoCompany);
            json.setMsg("true");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;

    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-5 下午17:25:51
     * 类介绍  :   详情
     * 构造参数:
     *
     */
    public ToJson<EnAutoCompany> selectById(Integer cid){
        ToJson<EnAutoCompany> json = new ToJson<>();
        try {
            EnAutoCompany enAutoCompany = enAutoCompanyMapper.selectById(cid);
            json.setObject(enAutoCompany);
            json.setMsg("true");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }

        /**
         *
         * 创建作者:   季佳伟
         * 创建日期:   2018-1-5 下午17:25:51
         * 类介绍  :   列表  或 导出 也可条件查询
         * 构造参数:
         *
         */
    public ToJson<EnAutoCompany> queryList(EnAutoCompany enAutoCompany, Integer page, Integer pageSize,
                                           boolean useFlag, HttpServletRequest request, HttpServletResponse response, String export){
        ToJson<EnAutoCompany> json = new ToJson<>();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            if(useFlag){
                map.put("page", pageParams);
            }
            map.put("enAutoCompany",enAutoCompany);
            if(export==null){
                export="0";
            }
            List<EnAutoCompany> enAutoCompanyList = enAutoCompanyMapper.selectList(map);
            json.setObj(enAutoCompanyList);
            json.setTotleNum(enAutoCompanyMapper.selectCount(enAutoCompany));
            json.setFlag(0);
            json.setMsg("ok");
            if (export.equals("1")){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("汽修企业信息", 8);
                String[] secondTitles = {"单位", "单位地址","联系人", "联系电话","主要产品及产量",
                        "核查生产开始时间","核查生产结束时间","备注"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"unit", "unitAddress","contact", "contactNum", "mainProduct",
                        "checkBeginTime","checkEndTime","note2"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, enAutoCompanyList, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "汽修企业信息记录表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-5 下午16:25:51
     * 类介绍  :   导入
     * 构造参数:
     *
     */
    public ToJson<EnAutoCompany> importEnAutoCompany(MultipartFile file, HttpServletResponse response,
                                                     HttpServletRequest request, HttpSession session) {
        ToJson<EnAutoCompany> json = new ToJson<>();
        Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        // 成功次数
        Integer successCount = 0;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            }else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
//                    // 将文件上传成功后进行读取文件
//                    // 进行读取的路径
//                    String readPath = path.append(newFileName).toString();
                    InputStream in =  file.getInputStream();
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    EnAutoCompany enAutoCompany = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        enAutoCompany = new EnAutoCompany();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //单位
                                            enAutoCompany.setUnit(cell.getStringCellValue());
                                            break;
                                        case 1:
                                            //单位地址
                                            enAutoCompany.setUnitAddress(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //联系人
                                            enAutoCompany.setContact(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            //联系电话
                                            if(cell.getCellType() == CellType.NUMERIC){
                                                cell.setCellType(CellType.STRING);
                                            }
                                            enAutoCompany.setContactNum(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //主要产品及产量
                                            enAutoCompany.setMainProduct(cell.getStringCellValue());
                                            break;
                                        case 5:
                                            //核查生产开始时间
                                            String result1 = null;
                                            if(cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                } else if (format == 20 || format == 32) {
                                                    //时间
                                                    sdf = new SimpleDateFormat("HH:mm");
                                                }else if (format == 22){
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date dates = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                result1 = sdf.format(dates);
                                                enAutoCompany.setCheckBeginTime(result1);
                                                break;
                                            }
                                            enAutoCompany.setCheckBeginTime(cell.getStringCellValue());
                                            break;
                                        case 6:
                                            //核查生产结束时间
                                            String result2 = null;
                                            if(cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                } else if (format == 20 || format == 32) {
                                                    //时间
                                                    sdf = new SimpleDateFormat("HH:mm");
                                                }else if (format == 22){
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date dates = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                result2 = sdf.format(dates);
                                                enAutoCompany.setCheckEndTime(result2);
                                                break;
                                            }
                                            enAutoCompany.setCheckEndTime(cell.getStringCellValue());
                                            break;
                                        case 7:
                                            //备注
                                            enAutoCompany.setNote2(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            enAutoCompany.setRemark1(mapOwnerinfoMapper.selectCoordingbyName(cell.getStringCellValue()));
                                            break;
                                        default:
                                            json.setFlag(0);
                                            json.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            enAutoCompany.setCreateUser(users.getUserId());
                            enAutoCompany.setCreateTime(DateFormat.getCurrentTime());
                            //将数据放入数据库
                            int count=enAutoCompanyMapper.insertSelective(enAutoCompany);
                            if(count>0) {
                                successCount = successCount + count;
                            }
                            dest.delete();
                        }
                    }

                }
            }
            if(successCount>0){
                json.setTotleNum(successCount);
                json.setMsg("ok");
                json.setFlag(0);
                return  json;
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setTotleNum(successCount+1);
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }


    }
